package com.test.dao;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

//动态查询
public class DynamicSpecifications {

	public static <T> Specification<T> bySearchFilter(final String identityNumber,  final String birthTime,  
			final String personName,final String gender) {
        return new Specification<T>() {

			@Override
			public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();  
                if (!StringUtils.isBlank(identityNumber)) {    ///该查询条件不为空时在sql语句中动态增加where条件
                    predicates.add(
                    		cb.equal(root.<String>get("identityNumber"), identityNumber));
                }
                if (!StringUtils.isBlank(birthTime)) {
                	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
                	String sd = birthTime +"-01-01";
                	String ed = birthTime +"-12-31";
                	Date startDate = null;
                	Date endDate = null;
					try {
						startDate = sdf.parse(sd);
						endDate = sdf.parse(ed);
					} catch (ParseException e) {
						e.printStackTrace();
					}
                    predicates.add(
                    		cb.between(root.<Date>get("birthTime"),startDate,endDate));
                }
                if (!StringUtils.isBlank(personName)) {
                    predicates.add(
                    		cb.like(root.<String>get("personName"), "%" + personName+ "%"));
                }
                if (!StringUtils.isBlank(gender)) {    ///该查询条件不为空时在sql语句中动态增加where条件
                    predicates.add(
                    		cb.equal(root.<String>get("gender"), gender));
                }
                // 将所有查询条件用 and 连接起来
            
                if (predicates.size() > 0) {
                         return cb.and(predicates.toArray(new Predicate[predicates.size()]));
                }
                return cb.conjunction();
			}
    };
	}
}
